
import uuid
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import insert, delete, text, select, update, desc
from model.{{Lower .structName}} import {{.structName}}
from initialization.crudInit import find_pojos, delete_pojo, update_pojo, insert_pojo
from utils.decorator import transaction_decorator, analysis_token_decorator
{{- range $fromName, $importName := .importNameMap}}
from {{$fromName}} import {{$importName}}
{{- end}}

class {{.structName}}:
    {{$len := .length}}
    def __init__(self, {{range $index, $value := .fieldNameList}}{{.FieldName}}{{if ne $index $len}}, {{end}}{{- end}}):
        {{- range .fieldNameList}}
        self.{{Lower .FieldName}} = {{Lower .FieldName}}
        {{- end}}

    @transaction_decorator
    async def add_{{Lower .structName}}(self, session: AsyncSession, o):
        o["id"] = uuid.uuid1().__str__()
        await insert_pojo(session, {{.structName}}, o)

    @transaction_decorator
    async def update_{{Lower .structName}}(self, session: AsyncSession, o):
        await update_pojo(session, {{.structName}}, o)

    @transaction_decorator
    async def delete_{{Lower .structName}}(self, session: AsyncSession, id):
        await delete_pojo(session, {{.structName}}, id)

    async def find_{{Lower .structName}}_one(session: AsyncSession, id) -> {{.structName}}:
        result = (await session.execute(
            select({{.structName}}).where({{.structName}}.id == id))).scalars().first()

        await session.close()

        return result

    async def find_{{Lower .structName}}_all(self, session: AsyncSession, o) -> list[{{.structName}}]:
        query = select({{.structName}})
        {{$classname := .structName}}
        {{- range .fieldNameList}}
        {{- if eq .isSave true}}
        if o.{{.FieldName}} != "":
            query = query.where({{$classname}}.{{.FieldName}}.like("%" + o.{{.FieldName}} + "%"))
        {{print}}
        {{- end}}
        {{- end}}
        if o.start_time != "":
            query = query.where({{.structName}}.created_at >= o.start_time)

        if o.end_time != "":
            query = query.where({{.structName}}.created_at <= o.end_time)

        pojos = await find_pojos(session, {{.structName}}, query, o)

        await session.close()

        return pojos

